/*
 * FXGL - JavaFX Game Library. The MIT License (MIT).
 * Copyright (c) AlmasB (almaslvl@gmail.com).
 * See LICENSE for details.
 */

package com.windea.study.kotlin.fxgl.sample.sandbox

import javafx.animation.*
import javafx.application.*
import javafx.scene.*
import javafx.scene.input.*
import javafx.scene.layout.*
import javafx.stage.*
import java.util.*

/**
 * @author Almas Baimagambetov (almaslvl@gmail.com)
 */
class TestApp : Application() {
	private val activeKeys = ArrayList<KeyData>()
	
	private fun createContent(): Parent {
		val timer = object : AnimationTimer() {
			override fun handle(now: Long) {
				
				val nowMillis = System.currentTimeMillis()
				
				val it = activeKeys.iterator()
				while(it.hasNext()) {
					val data = it.next()
					
					if(nowMillis - data.timePressedMillis > DOUBLE_PRESS_DELAY_MILLIS) {
						onSinglePress(data.key)
						it.remove()
					}
				}
			}
		}
		timer.start()
		
		return Pane()
	}
	
	private class KeyData internal constructor(val key: KeyCode, val timePressedMillis: Long)
	
	@Throws(Exception::class)
	override fun start(stage: Stage) {
		val scene = Scene(createContent(), 800.0, 600.0)
		scene.setOnKeyPressed { event ->
			val key = event.code
			val now = System.currentTimeMillis()
			
			val keyAlreadyPressed = activeKeys.stream()
				.anyMatch { data -> data.key == key }
			
			if(keyAlreadyPressed) {
				onDoublePress(key)
				activeKeys.removeIf { data -> data.key == key }
			} else {
				activeKeys.add(KeyData(key, now))
			}
		}
		
		stage.scene = scene
		stage.show()
	}
	
	private fun onSinglePress(key: KeyCode) {
		println("Single press: $key")
	}
	
	private fun onDoublePress(key: KeyCode) {
		println("Double press: $key")
	}
	
	companion object {
		private const val DOUBLE_PRESS_DELAY_MILLIS = 150
	}
}

fun main(args: Array<String>) {
	Application.launch(TestApp::class.java, *args)
}
